﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 门诊结算服务
    /// </summary>
    public class OutpatientDocInfoService
    {
        /// <summary>
        /// 2201 门诊挂号
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputOutpatientRregistration> OutpatientRregistration(FsiRequestHeader<InputOutpatientRregistration> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string psn_no = fsiRequest.Input.data.psn_no;
            string ipt_otp_no = fsiRequest.Input.data.ipt_otp_no;

            if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || string.IsNullOrEmpty(ipt_otp_no))
            {
                throw new Exception("参数校验失败：传入的机构代码|人员编号|住院/门诊号为空，请检查入参！");
            }

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";

            using (var conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                DataTable dtpsninfo = new DataTable();
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtpsninfo.Load(reader);
                            if (dtpsninfo.Rows.Count != 1)
                            {
                                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                            }
                            cmd.Parameters.Clear();
                        }
                        //设置就诊id
                        string mdtrt_id;

                        //浙江省 如果是异地 则结算id需要短一点，不然会报错 模拟异地的结算id长度 取人员参保地长度前四位是否和入参参保地前四位是否一致
                        if ( fsiRequest.insuplc_admdvs.Substring(0, 4) != fsiRequest.mdtrtarea_admvs.Substring(0, 4))
                        {
                            mdtrt_id = $"{dtunix}";
                        }
                        else
                        {
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                        }

                        var output = new OutputOutpatientRregistration
                        {
                            data = new OutpatientRregistration
                            {
                                mdtrt_id = mdtrt_id,
                                psn_no = psn_no,
                                ipt_otp_no = ipt_otp_no
                            }
                        };
                        string OutputJson = JsonConvert.SerializeObject(output);
                        string InputJson = JsonConvert.SerializeObject(fsiRequest);
                        cmd.Transaction = transaction;
                        try
                        {

                            // 插入挂号记录
                            cmd.CommandText = "INSERT INTO `data`.`fsi_hospital_register` ( `fixmedins_code`, `fixmedins_name`, `register_state`, `psn_no`, `insutype`, " +
                                              "`begntime`, `ipt_otp_no`, `mdtrt_id`, `atddr_no`, `dr_name`, `dept_code`, `dept_name`, `caty`, `exp_content`, " +
                                              "`outpatientRregistrationInput`, `outpatientRregistrationOutput`, `outpatientRegistrationCancelInput`, " +
                                              "`outpatientRegistrationCancelOutput`, `create_time`, `update_time`) " +
                                              "VALUES ( @fixmedins_code, @fixmedins_name, @register_state, @psn_no, @insutype, @begntime, @ipt_otp_no, " +
                                              "@mdtrt_id, @atddr_no, @dr_name, @dept_code, @dept_name, @caty, @exp_content, " +
                                              "@outpatientRregistrationInput, @outpatientRregistrationOutput, @outpatientRegistrationCancelInput, " +
                                              "@outpatientRegistrationCancelOutput, @create_time, @update_time);";
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@register_state", 0);
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            cmd.Parameters.AddWithValue("@insutype", fsiRequest.Input.data.insutype);
                            cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.data.begntime);
                            cmd.Parameters.AddWithValue("@ipt_otp_no", fsiRequest.Input.data.ipt_otp_no);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                            cmd.Parameters.AddWithValue("@atddr_no", fsiRequest.Input.data.atddr_no);
                            cmd.Parameters.AddWithValue("@dr_name", fsiRequest.Input.data.dr_name);
                            cmd.Parameters.AddWithValue("@dept_code", fsiRequest.Input.data.dept_code);
                            cmd.Parameters.AddWithValue("@dept_name", fsiRequest.Input.data.dept_name);
                            cmd.Parameters.AddWithValue("@caty", fsiRequest.Input.data.caty);
                            cmd.Parameters.AddWithValue("@exp_content", fsiRequest.Input.data.exp_content);
                            cmd.Parameters.AddWithValue("@outpatientRregistrationInput", InputJson);
                            cmd.Parameters.AddWithValue("@outpatientRregistrationOutput", OutputJson);
                            cmd.Parameters.AddWithValue("@outpatientRegistrationCancelInput", "");
                            cmd.Parameters.AddWithValue("@outpatientRegistrationCancelOutput", "");
                            cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH:mm:ss"));

                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();

                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"门诊挂号处理失败：插入挂号记录表失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        transaction.Commit();
                        return output;
                    }
                }
            }
        }
        /// <summary>
        /// 2202 门诊挂号撤销
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> OutpatientRegistrationCancel(FsiRequestHeader<InputOutpatientRegistrationCancel> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string fixmedins_code = fsiRequest.fixmedins_code;
            string psn_no = fsiRequest.Input.data.psn_no;
            string mdtrtid = fsiRequest.Input.data.mdtrt_id;
            string ipt_otp_no = fsiRequest.Input.data.ipt_otp_no;
            if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(mdtrtid) || string.IsNullOrEmpty(ipt_otp_no))
            {
                throw new Exception("参数校验失败：传入的住院/门诊号|人员编号||就诊ID为空，请检查入参！");
            }

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";

            using (var conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                DataTable dtpsninfo = new DataTable();
                DataTable dt = new DataTable();
                string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtpsninfo.Load(reader);
                            if (dtpsninfo.Rows.Count != 1)
                            {
                                throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                            }
                            cmd.Parameters.Clear();
                        }
                        cmd.CommandText = "select * from fsi_hospital_register where psn_no=@psn_no and mdtrt_id=@mdtrt_id and ipt_otp_no=@ipt_otp_no and register_state=0";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                        cmd.Parameters.AddWithValue("@ipt_otp_no", ipt_otp_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count != 1)
                            {
                                throw new Exception($"查询挂号记录信息表失败！查询到的挂号记录总数为：{dt.Rows.Count}");
                            }
                            cmd.Parameters.Clear();
                        }
                        string InputJson = JsonConvert.SerializeObject(fsiRequest);
                        cmd.Transaction = transaction;
                        try
                        {
                            cmd.CommandText = "update fsi_hospital_register  set register_state= @register_state,outpatientRegistrationCancelInput=@outpatientRegistrationCancelInput,outpatientRegistrationCancelOutput=@outpatientRegistrationCancelOutput,update_time=@update_time where psn_no=@psn_no and mdtrt_id=@mdtrt_id and ipt_otp_no=@ipt_otp_no and register_state=0";
                            cmd.Parameters.AddWithValue("@register_state", 2);
                            cmd.Parameters.AddWithValue("@outpatientRegistrationCancelInput", InputJson);
                            cmd.Parameters.AddWithValue("@outpatientRegistrationCancelOutput", "");
                            cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            cmd.Parameters.AddWithValue("@mdtrt_id", mdtrtid);
                            cmd.Parameters.AddWithValue("@ipt_otp_no", ipt_otp_no);
                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"门诊挂号数据处理失败：更新门诊挂号记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        transaction.Commit();
                        return true;
                    }
                }
            }
        }
        /// <summary>
        /// 2203 门诊就诊信息上传
        /// </summary>
        /// <param name="fsiRequest">入参</param>
        /// <param name="CountrollerName">来源控制器名称</param>
        /// <returns>出参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> OutpatientMdtrtinfoUp(FsiRequestHeader<InputOutpatientMdtrtinfoUpA> fsiRequest, string CountrollerName)
        {
            string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
            string mdtrt_id = fsiRequest.Input.mdtrtinfo.mdtrt_id;
            string psn_no = fsiRequest.Input.mdtrtinfo.psn_no;

            if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || string.IsNullOrEmpty(mdtrt_id))
            {
                throw new Exception("参数校验失败：传入的机构代码|人员编号|就诊ID为空，请检查入参！");
            }

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";

            using (var conn = new MySqlConnection(connectionString))
            {
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                DataTable dtpsninfo = new DataTable();
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                await conn.OpenAsync();
                using (MySqlTransaction transaction = conn.BeginTransaction())
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_hospital_register where psn_no=@psn_no and register_state=0 and mdtrt_id=@mdtrt_id";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtpsninfo.Load(reader);
                            if (dtpsninfo.Rows.Count != 1)
                            {
                                throw new Exception($"查询挂号记录表失败！查询到的未撤销的挂号记录总数为：{dtpsninfo.Rows.Count}");
                            }
                            cmd.Parameters.Clear();
                        }
                        string InputJson = JsonConvert.SerializeObject(fsiRequest);
                        cmd.Transaction = transaction;
                        try
                        {
                            cmd.CommandText = "INSERT INTO `data`.`fsi_hospital_uploadmedicalrecords` (`fixmedins_code`, `fixmedins_name`, `mdtrt_id`, `psn_no`, `med_type`, `begntime`, `main_cond_dscr`, `dise_codg`, `dise_name`, `diseinfo`, `outpatientMdtrtinfoUpInput`, `outpatientMdtrtinfoUpOutput`, `create_time`, `update_time`) " +
                            "VALUES (@fixmedins_code, @fixmedins_name, @mdtrt_id, @psn_no, @med_type, @begntime, @main_cond_dscr, @dise_codg, @dise_name, @diseinfo, @outpatientMdtrtinfoUpInput, @outpatientMdtrtinfoUpOutput, @create_time, @update_time);";
                            cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                            cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                            cmd.Parameters.AddWithValue("@mdtrt_id", fsiRequest.Input.mdtrtinfo.mdtrt_id);
                            cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.mdtrtinfo.psn_no);
                            cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.mdtrtinfo.med_type);
                            cmd.Parameters.AddWithValue("@begntime", fsiRequest.Input.mdtrtinfo.begntime);
                            cmd.Parameters.AddWithValue("@main_cond_dscr", fsiRequest.Input.mdtrtinfo.main_cond_dscr);
                            cmd.Parameters.AddWithValue("@dise_codg", fsiRequest.Input.mdtrtinfo.dise_codg);
                            cmd.Parameters.AddWithValue("@dise_name", fsiRequest.Input.mdtrtinfo.dise_name);
                            cmd.Parameters.AddWithValue("@diseinfo", JsonConvert.SerializeObject(fsiRequest.Input.diseinfo));
                            cmd.Parameters.AddWithValue("@outpatientMdtrtinfoUpInput", InputJson);
                            cmd.Parameters.AddWithValue("@outpatientMdtrtinfoUpOutput", "");
                            cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                            cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));

                            await cmd.ExecuteNonQueryAsync();
                            cmd.Parameters.Clear();

                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            throw new Exception($"门诊就诊信息上传失败：插入门诊就诊信息记录表失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                        }
                        transaction.Commit();
                        return true;
                    }
                }
            }
        }

    }
}
